<template>
  <div id="teamPage">
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <!-- 队伍名 -->
        <van-field
            v-model="addTeamData.name"
            name="name"
            label="队伍名"
            placeholder="请输入队伍名"
            :rules="[{ required: true, message: '请输入队伍名' }]"
        />
        <!-- 队伍描述 -->
        <van-field
            v-model="addTeamData.description"
            rows="4"
            autosize
            label="队伍描述"
            type="textarea"
            placeholder="请输入队伍描述"
        />

        <!-- 过期时间 -->
        <van-field
            v-model="currentDate"
            is-link
            readonly
            name="datePicker"
            label="过期时间"
            :placeholder="addTeamData.expireTime ? formatDate(addTeamData.expireTime) : '点击选择过期时间'"
            @click="showPicker = true"
        />
        <!-- 时间选择器 -->
        <van-popup v-model:show="showPicker" destroy-on-close position="bottom">
          <van-date-picker
              title="请选择日期"
              :min-date="minDate"
              @confirm="onConfirmDate"
              @cancel="showPicker = false"
          />
        </van-popup>
        <!-- 最大人数 -->
        <van-field name="stepper" label="最大人数">
          <template #input>
            <van-stepper v-model="addTeamData.maxNum" :max="10" :min="3" />
          </template>
        </van-field>
        <!-- 队伍状态 -->
        <van-field name="radio" label="队伍状态">
          <template #input>
            <van-radio-group v-model="addTeamData.status" direction="horizontal">
              <van-radio :name="0">公开</van-radio>
              <van-radio :name="1">私有</van-radio>
              <van-radio :name="2">加密</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <!-- 密码输入框（仅当状态为加密时显示） -->
        <van-field
            v-if="Number(addTeamData.status) === 2"
            v-model="addTeamData.password"
            type="password"
            name="password"
            label="密码"
            placeholder="请输入队伍密码"
            :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <!-- 提交按钮 -->
      <div style="margin: 16px">
        <van-button :loading="loading" round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import myAxios from '../plugins/myAxios.ts';
import { showSuccessToast, showFailToast } from 'vant';
import dayjs from 'dayjs'; // 引入 dayjs 用于日期格式化

const router = useRouter();
const route = useRoute();

// 初始化表单数据
const initFormData = {
  name: '',
  description: '',
  expireTime: '',
  maxNum: 3, // 默认最小人数
  password: '',
  status: 0, // 默认公开
};
const addTeamData = ref({ ...initFormData });

// 控制日期选择器的显示
let showPicker = ref(false);
const minDate = new Date(2020, 0, 1);
let currentDate = ref(''); // 当前选择的日期

// 加载状态
const loading = ref(false);


onMounted(async () => {
  // 获取队伍信息
  const id = route.params.teamId;
  console.log("teamId Update"+id);
  if (id <= 0) {
    showFailToast('加载队伍失败，请重试');
    return;
  }
  try {
    const res = await myAxios.get('/team/get', {
      params: {
        id,
      },
    });

    if (res?.code === 0) {
      addTeamData.value = res.data;
      currentDate.value = new Date(res.data.expireTime); // 初始化日期选择器
    } else {
      showFailToast('加载队伍失败，请重试');
    }
  } catch (error) {
    showFailToast('加载队伍失败，请重试');
  }
});

// 日期选择确认
const onConfirmDate = ({ selectedValues }) => {
  currentDate  = selectedValues.join('/');
  addTeamData.value.expireTime = selectedValues; // 组合日期和时间
  showPicker.value = false;
};


// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD');
};


// 提交表单
const onSubmit = async () => {
  // 数据校验
  if (!addTeamData.value.name) {
    showFailToast('请输入队伍名');
    return;
  }
  if (!addTeamData.value.expireTime) {
    showFailToast('请选择过期时间');
    return;
  }
  if (Number(addTeamData.value.status) === 2 && !addTeamData.value.password) {
    showFailToast('请填写密码');
    return;
  }

  //
  const postData = {
    ...addTeamData.value,
    status: Number(addTeamData.value.status),
    expireTime: formatDate(addTeamData.value.expireTime),
  };
  // 提交数据
  loading.value = true;
  try {
    const res = await myAxios.post('/team/update', postData);
    if (res?.code === 0 && res.data) {
      showSuccessToast('更新成功');
      router.push({ path: '/team', replace: true });
    } else {
      showFailToast(res?.message || '更新失败');
    }
  } catch (error) {
    showFailToast('请求失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
#teamPage {
  padding: 16px;
}
</style>